package zjut.raymond.collectorplus.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import zjut.raymond.collectorplus.R;
import zjut.raymond.collectorplus.adapter.ReferencePointListAdapter;
import zjut.raymond.collectorplus.pojo.ReferencePoint;
import zjut.raymond.collectorplus.util.ApiResult;
import zjut.raymond.collectorplus.util.Constant;
import zjut.raymond.collectorplus.view.CustomTitleView;
import zjut.raymond.collectorplus.vm.MainViewModel;

public class MainFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "MainFragment";
    public static final int MSG_REQUEST = 0x91;
    public static final int MSG_UPDATE_UI = 0x92;
    private MainViewModel mViewModel;
    private CustomTitleView customTitleView;
    private TextView tvAreaInfo;//, tvTips;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerViewRP;
    private Button btnAddOne, btnAddBatch, btnFresh;
    private ReferencePointListAdapter referencePointListAdapter;
    private ExecutorService executorService;
    public static Handler handler;
    private AddRPDialog addRPDialog = new AddRPDialog();
    private AddBatchRPDialog addBatchRPDialog = new AddBatchRPDialog();

    public MainFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main_fragment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(getActivity()).get(MainViewModel.class);
        executorService = Executors.newScheduledThreadPool(10);
        intiHandler();
        initView();
    }

    private void intiHandler() {
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case MSG_REQUEST: {
                        mViewModel.clearReferencePointList();
                        executorService.execute(requestRunnable);
                        break;
                    }
                    case MSG_UPDATE_UI: {
                        swipeRefreshLayout.setRefreshing(false);
                        if (mViewModel.getRpSize() > 0) {
                            List<ReferencePoint> referencePoints = mViewModel.getReferencePointLiveData().getValue();
                            referencePointListAdapter.setReferencePoints(referencePoints);
                            referencePointListAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getContext(), "参考点列表为空", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    default: {
                        super.handleMessage(msg);
                        break;
                    }
                }
            }
        };
    }

    private void initView() {
        customTitleView = getView().findViewById(R.id.title_main_fragment);
        customTitleView.setLeftOnClickListener(v -> {
            NavController controller = Navigation.findNavController(v);
            controller.navigate(R.id.action_mainFragment_to_areaSelectedFragment);
            mViewModel.clearReferencePointList();
        });
        tvAreaInfo = getView().findViewById(R.id.tv_area_info);
        tvAreaInfo.setText(mViewModel.getAreaInfo());
        btnAddOne = getView().findViewById(R.id.btn_add_one);
        btnAddBatch = getView().findViewById(R.id.btn_add_batch);
        btnFresh = getView().findViewById(R.id.btn_fresh);
        btnAddOne.setOnClickListener(this);
        btnAddBatch.setOnClickListener(this);
        btnFresh.setOnClickListener(this);
        swipeRefreshLayout = getView().findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(() -> {
            if (mViewModel.areaSelected()) {
                handler.sendEmptyMessage(MSG_REQUEST);
            } else {
                Toast.makeText(getContext(), "请先选择区域信息", Toast.LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }

        });

        recyclerViewRP = getView().findViewById(R.id.recyclerViewRP);
        recyclerViewRP.setLayoutManager(new LinearLayoutManager(getContext()));
        referencePointListAdapter = new ReferencePointListAdapter(getContext());
        recyclerViewRP.setAdapter(referencePointListAdapter);
        if (mViewModel.areaSelected() && mViewModel.getRpSize() <= 0) {
            handler.sendEmptyMessage(MSG_REQUEST);
        } else {
            handler.sendEmptyMessage(MSG_UPDATE_UI);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add_one:{
                if (mViewModel.areaSelected()) {
                    addRPDialog.show(getParentFragmentManager(), "AddOneDialog");
                } else {
                    Toast.makeText(getContext(), "请先选择区域信息", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.btn_add_batch:{
                if (mViewModel.areaSelected()) {
                    addBatchRPDialog.show(getParentFragmentManager(), "AddBatchRPDialog");
                } else {
                    Toast.makeText(getContext(), "请先选择区域信息", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.btn_fresh:{
                if (mViewModel.areaSelected()) {
                    handler.sendEmptyMessage(MSG_REQUEST);
                } else {
                    Toast.makeText(getContext(), "请先选择区域信息", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            default:
                break;
        }
    }

    Runnable requestRunnable = new Runnable() {
        @Override
        public void run() {
            RequestParams params = new RequestParams();
            params.addFormDataPart("business_id", Objects.requireNonNull(mViewModel.getCurrentBusiness().getValue()).getId());
            params.addFormDataPart("area_id", Objects.requireNonNull(mViewModel.getCurrentBuilding().getValue()).getId());
            params.addFormDataPart("floor_id", Objects.requireNonNull(mViewModel.getCurrentFloor().getValue()).getId());
            params.addFormDataPart("size", 9999);
            HttpRequest.get(Constant.RQ_REFERENCE_POINT_URL, params, new BaseHttpRequestCallback<ApiResult>() {
                @Override
                protected void onSuccess(ApiResult apiResult) {
                    Log.d(TAG, "onSuccess: " + JSON.toJSONString(apiResult.getData()));
                    JSONObject dataJo = JSON.parseObject(JSON.toJSONString(apiResult.getData()));
                    JSONObject list = JSON.parseObject(dataJo.getString("list"));
                    JSONArray records = JSONArray.parseArray(list.getString("records"));
                    if (records.size() > 0) {
                        for (Object object : records) {
                            if (object instanceof JSONObject) {
                                JSONObject jsonObject = (JSONObject) object;
                                String id = jsonObject.getString("id");
                                String coord = jsonObject.getString("coord");
                                Integer status = jsonObject.getInteger("status");
                                mViewModel.addReferencePoint(new ReferencePoint(Integer.parseInt(id), coord, status));
                                Log.d(TAG, "onSuccess: " + mViewModel.getRpSize());
                            }
                        }
                    }
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    handler.sendEmptyMessage(MSG_UPDATE_UI);
                }
            });
        }
    };
}